package com.titaniume.rqbbitmq.four;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.titaniume.rqbbitmq.util.RabbitMqUtils;

import java.lang.reflect.Member;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * @ProjectName: rqbbitmq-hello
 * @Package: com.titaniume.rqbbitmq.four
 * @ClassName: ConfirmMessage
 * @Author: titan
 * @Description:
 *  发布去确认模式
 *  1.单个确认
 *  2.批量确认
 *  3.异步确认
 *
 * @Date: 2021/12/20 21:50
 * @Version: 1.0
 */
public class ConfirmMessage {


    //批量发送消息的个数
    public  static final int MESSAGE_COUNT = 1000;

    public static void main(String[] args) throws Exception {
         //1.单个确认
         //ConfirmMessage.pulishMessageIndividually(); //发布1000个单独确认消息，耗时27887ms
         //2.批量确认
         // ConfirmMessage.pushlishMessageBatch(); //发布1000批量确认消息，耗时814ms
         //3.异步确认
        ConfirmMessage.pushlishMessageAsync(); //发布1000个异步发布确认消息，耗时61ms

    }

    //1.单个确认
    public static void  pulishMessageIndividually() throws  Exception{

        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();
        //开始时间
        long begin = System.currentTimeMillis();

        //批量发送消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("",queueName,null,message.getBytes());
            //单个消息就马上进行发布确认
            boolean flag = channel.waitForConfirms();
            if (flag) {
                System.out.println("消息发送成功");
            }
        }
        //结束世界
        long end = System.currentTimeMillis();
        System.out.println("发布"+ MESSAGE_COUNT +"个单独确认消息，耗时" + (end - begin)+"ms");

    }

    //2.批量发布确认
    public static void  pushlishMessageBatch() throws  Exception{

        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();

        //批量确认消息大小
        int batchSize =100;

        //开始时间
        long begin = System.currentTimeMillis();

        //批量发送消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("",queueName,null,message.getBytes());
            //判断达到100条消息时候批量确认一次
            if(i % batchSize == 0){
                channel.waitForConfirms();
            }
        }
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+ MESSAGE_COUNT +"批量确认消息，耗时" + (end - begin)+"ms");

    }


    //3.异步确认发布
    public static void  pushlishMessageAsync() throws  Exception{

        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();

        /**
         *
         * 线程安全有序的一个哈希表，适用于高并发
         * 1.轻松将序号和消息绑定关联
         * 2.轻松删除条目 只要给到序号
         * 3.支持并发访问
         */
        ConcurrentSkipListMap<Long,String> outstandingConfirms = new ConcurrentSkipListMap();
        //消息确认成功 回调函数
        /**
         * 1.消息的标记
         * 2.是否为批量确认
         */
        ConfirmCallback ackCallback = (deliverypTag, multiple) -> {
            if (multiple){
                //2.删除已经确认的消息 剩下的就是未确认的消息
                ConcurrentNavigableMap<Long, String> confirmed = outstandingConfirms.headMap(deliverypTag);
                //清除该部分未确认消息
                confirmed.clear();
            }else{
                 outstandingConfirms.remove(deliverypTag);
            }
            System.out.println("确认消息:" + deliverypTag);
        };

        //消息确认失败 回调函数
        /**
         * 1.消息的标记
         * 2.是否为批量确认
         *
         */
        ConfirmCallback nackCallback = (deliverypTag, multiple) -> {
            //3.打印一下未确认消息有哪些
            String message = outstandingConfirms.get(deliverypTag);
            System.out.println("未确认消息:" + message +"未确认消息tag:"+ deliverypTag);
        };


        //准备消息监听 监听哪些消息成功了 哪些消息失败了
        channel.addConfirmListener(ackCallback,nackCallback);


        //开始时间
        long begin = System.currentTimeMillis();
        //批量发送消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("",queueName,null,message.getBytes());
            // 1.此处记录所有要发送的消息总和
            outstandingConfirms.put(channel.getNextPublishSeqNo(),message);
        }
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+ MESSAGE_COUNT +"个异步发布确认消息，耗时" + (end - begin) +"ms");

    }




}
